import pathlib
import time

import util

import pandas as pd
import akshare as ak
from pyecharts.charts import Line
from pyecharts.globals import ThemeType
import pyecharts.options as opts

from 网格计划 import model

stockIdx = model.get_bai_jiu_stock_index_info()
indexName = '中国教育'  # 指数名称
fundCode = '513360'   # 基金代码
startPercent = 30   # 回撤达到多少开始网格
step = 5    # 网格步长
perMoney = 1000     # 每份金额

startDate = "20010101"
df = ak.fund_etf_hist_em(symbol=fundCode, start_date=startDate, adjust="qfq")
rs = df.describe()
max, min = rs['最高']['max'], rs['最低']['min']

dataDir = pathlib.Path(f'./data/{indexName}')
pathlib.Path(dataDir).mkdir(parents=True, exist_ok=True)

gridDf = util.getGridPlan(maxValue=max, minValue=min, step=step, startPercent=startPercent, money=perMoney)
print(gridDf)
date = time.strftime('%Y%m%d', time.localtime())

# 绘制图表 - 折线图
chart = Line(
    # 设置主题、画布宽度、高度等信息
    init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
)

# 全局设置
chart.set_global_opts(
    title_opts=opts.TitleOpts(title=f'{indexName}-基金列表'),
    # 工具箱配置
    toolbox_opts=opts.ToolboxOpts(is_show=True),
    # 区域缩放配置
    datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
    # y轴配置
    yaxis_opts=opts.AxisOpts(
        min_=round(min * 0.9, 2),  # 设置y轴刻度间隔为20
    )
)

chart.add_xaxis(xaxis_data=df["日期"].tolist())  # 添加x轴数据

markLineList = []
for index, row in gridDf.iterrows():
    if row['加仓批次'] == 0:
        continue
    price = round(row['基金价格'], 3)
    markLineList.append(opts.MarkLineItem(name=f"第{int(row['加仓批次'])}网-回撤:{row['回撤比例%']}%", y=f'{price}'))

chart.add_yaxis(
    series_name=fundCode,
    y_axis=df['收盘'].tolist(),  # y轴数据
    is_connect_nones=True,  # 连接空数据
    markpoint_opts=opts.MarkPointOpts(
        data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
    ),
    markline_opts=opts.MarkLineOpts(
        data=markLineList
    ),

)

date = time.strftime('%Y%m%d', time.localtime(time.time()))
chart.render(f"{dataDir}/{indexName}-{fundCode}-{date}基金历史行情.html")
